package com.sabre.workshop.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A singleton to obtain an EntityManager object from a proper factory.
 * The factory is bound to a single persistence unit and this class can only 
 * handle one persistence unit.
 * 
 * @author mgore
 *
 */
public class EntityManagerUtilSingleton {

	static {
		// Leave room here to add Dependency Injection of PU's name.
		PERSISTENCE_UNIT_NAME = "Sabre-Taller";
	}
	
	private final static String PERSISTENCE_UNIT_NAME;
	
	private Log log = LogFactory.getFactory().getInstance(this.getClass());

	private static EntityManagerUtilSingleton instance = new EntityManagerUtilSingleton();

	private EntityManagerFactory entityManagerFactory;

	// private ThreadLocal<EntityManager> threadLocalEntityManager;

	private EntityManagerUtilSingleton() {

		// threadLocalEntityManager = new ThreadLocal<EntityManager>();
	}

	public static EntityManagerUtilSingleton getInstance() {
		return instance;
	}

	private EntityManagerFactory getEntityManagerFactory() {

		if (entityManagerFactory == null) {

			entityManagerFactory = Persistence
					.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		}

		return entityManagerFactory;
	}

	public EntityManager getEntityManager() {

		// EntityManager entityManager = threadLocalEntityManager.get();
		//		
		// if (entityManager == null) {
		//			
		// entityManager = this.getEntityManagerFactory().createEntityManager();
		// threadLocalEntityManager.set(entityManager);
		// }

		EntityManager entityManager = this.getEntityManagerFactory()
				.createEntityManager();
		log.trace("Giving out " + entityManager);

		return entityManager;
	}

	// public void closeAndDestroyEntityManager() {
	//
	// EntityManager entityManager = threadLocalEntityManager.get();
	//
	// if (entityManager != null) {
	//
	// log.trace("Closing " + entityManager);
	//
	// entityManager.close();
	// threadLocalEntityManager.set(null);
	// entityManager = null;
	// }
	// else {
	//
	// log.trace("No EntityManager instance. Nothing to close.");
	//		}
	//	}
}
